package com.baidu.foody.viewmodel

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.baidu.foody.data.remote.NetworkConstants
import com.baidu.foody.data.remote.Repository
import com.baidu.foody.util.NetworkResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainViewModel(application: Application): AndroidViewModel(application) {
    private val repository = Repository()

    //自己内部操作可变 暴露给外部是不可变的
    private val _networkResult:MutableLiveData<NetworkResult> = MutableLiveData()
    val networkResult: LiveData<NetworkResult> = _networkResult

    //记录当前网络状态
    var networkAvailable = false

    init {
        observeNetworkStatus()
    }

    /**
     * 实时监听网络数据
     */
    private fun observeNetworkStatus(){
        //获得网络连接的管理器对象
        val connectManager = getApplication<Application>()
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        //注册网络状态的监听器
        connectManager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback(){
            override fun onAvailable(network: Network) {
                networkAvailable = true
            }

            override fun onLost(network: Network) {
                networkAvailable = false
            }
        })
    }

    /**
     * 加载食谱
     */
    fun loadFoodRecipes(query:String = "meat", diet: String = "whole30", type: String = "main course"){
        val queryMap = mapOf(
            NetworkConstants.QUERY_KEY to query,
            NetworkConstants.DIET_KEY to diet,
            NetworkConstants.TYPE_KEY to type,
            NetworkConstants.ADD_INFORMATION_KEY to "true",
            NetworkConstants.FILL_INGREDIENTS_KEY to "true",
            NetworkConstants.NUMBER_KEY to NetworkConstants.NUMBER,
            NetworkConstants.API_KEY to NetworkConstants.APIKEY
        )

        //进入加载状态
        _networkResult.value = NetworkResult.Loading

        viewModelScope.launch(Dispatchers.IO) {
            repository.getFoodRecipes(queryMap).also { response ->
                var result:NetworkResult
                if (response.isSuccessful){
                    //请求成功
                    val data = response.body()
                    result = if (data == null) {
                        NetworkResult.Failure("数据没找到")
                    }else{
                        if (data.results.isNullOrEmpty()){
                            NetworkResult.Failure("数据不存在")
                        }else{
                            NetworkResult.Success(data)
                        }
                    }
                }else{
                    //请求失败
                    result = when{
                        response.message().contains("timeout") -> NetworkResult.Failure("请求超时")
                        response.code() == 402 -> NetworkResult.Failure("appkey格式不正确")
                        else -> NetworkResult.Failure("请求失败 请求检查请求地址是否正确")
                    }
                }

                _networkResult.postValue(result)
            }
        }

    }

    /**
     * 检查是否有网络
     */
    @RequiresApi(Build.VERSION_CODES.S)
    fun checkNetworkConnection():Boolean{
        //获取网络连接的管理器
        val cm = getApplication<Application>().applicationContext
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        //获取当前可用的网络
        val network = cm.activeNetwork ?: return false
        val capabilities = cm.getNetworkCapabilities(network) ?: return false
        //可以获取网络的类型 WIFI 蜂窝 热点
        //capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        //capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        //capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    }

}